package org.ns.tomdog.server.support;

import org.ns.tomdog.search.FuzzySearch;
import org.ns.tomdog.server.WebAppContainer;
import org.ns.tomdog.server.WebAppContext;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebAppContainerStartup implements WebAppContainer {

    private Map<String, WebAppContext> webAppsMap = new ConcurrentHashMap<>();
    private List<WebAppContext> webAppContexts;
    private FuzzySearch contextSearch = new FuzzySearch();
    private String host;
    private String bastPath;

    public WebAppContainerStartup(String host, String bastPath, List<WebAppContext> webAppContexts) {
        this.host = host;
        this.bastPath = bastPath;
        for (WebAppContext webAppContext : webAppContexts) {
            contextSearch.add(webAppContext.getContextPath(), webAppContext);
        }
        this.webAppContexts = webAppContexts;
    }

    @Override
    public String getHost() {
        return host;
    }

    @Override
    public String getBasePath() {
        return bastPath;
    }

    @Override
    public WebAppContext getWebAppContext(String url) {
        WebAppContext webAppContext = this.webAppsMap.get(url);
        if (webAppContext == null) {
            webAppContext = (WebAppContext) contextSearch.searchPrefix(url);
            if (webAppContext != null) {
                this.webAppsMap.put(url, webAppContext);
            }
        }
        return webAppContext;
    }

    @Override
    public void init() {

        for (WebAppContext webAppContext : webAppContexts) {
            webAppContext.init();
        }
    }

    @Override
    public void start() {
        for (WebAppContext webAppContext : webAppContexts) {
            webAppContext.start();
        }
    }
}
